import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElMessageBox
} from "element-plus";
import {
  createRbacMenuApi,
  updateRbacMenuApi,
  delRbacMenuApi,
  getRbacMenuShowApi,
  getRbacMenuListApi,
  getRbacMenuListTreeApi,
  updateUserStatusApi,
} from "@/api/user";
export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 10,
    keyword: "",
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const menuListTree = ref()
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const indexMethod = (index: number) => {
    return index + 1;
  };
  const getStatusType = (type, text = false) => {
    switch (type) {
      case 0:
        return text ? "未审核" : "danger";
      case 1:
        return text ? "启用" : "primary";
      case 2:
        return text ? "禁用" : "info";
    }
  };
  const columns: TableColumnList = [
    {
      label: "菜单名称",
      prop: "name",
	   align: "left",
    },
    {
      label: "菜单等级",
      prop: "levelName",
	  // formatter:({level})=> {
	  // 	return level === 1?'一级菜单':'二级菜单'
	  // }
    },
    // {
    //   label: "路径",
    //   prop: "menuPath"
    // },
	{
	  label: "图标标识",
	  prop: "icon"
	},
	{
	  label: "状态",
	  prop: "status",
	 //  cellRenderer: ({ row, props }) => (
		//   <el-tag
		// 	size={props.size}
		// 	type={row.status === 2 ? "danger" : null}
		// 	effect="plain"
		//   >
		// 	{row.status === 1 ? "启用" : "禁用"}
		//   </el-tag>
		// )
	  cellRenderer: scope => (
	  	<el-switch
	  	  size={scope.props.size === "small" ? "small" : "default"}
	  	  v-model={scope.row.status}
	  	  active-value={1}
	  	  inactive-value={2}
	  	  active-text="启用"
	  	  inactive-text="禁用"
	  	  inline-prompt
	  	  onClick={() => switchStatus(scope as any)}
	  	/>
	  )
	},
	{
	  label: "链接类型",
	  prop: "linkType",
	  formatter:({linkType})=> {
	  	return linkType === 1?'内部链接':'外部链接'
	  }
	},
	{
	  label: "是否为页面菜单",
	  prop: "isPageMenu",
	  formatter:({isPageMenu})=> {
	  	return isPageMenu === 1?'是':'否'
	  }
	},
	// {
	//   label: "链接地址",
	//   prop: "linkUrl"
	// },
	{
	  label: "排序",
	  prop: "sort"
	},
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ];
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getRbacMenuListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = 1;
    });
    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    getRbacMenuListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = result.result.current_page;
    });
    setTimeout(() => {
      loading.value = false;
    }, 150);
  }
  /** 启用/停用*/
  function switchStatus ({ row }) {
  	ElMessageBox.confirm(
  	  `确认要<strong>${
  		row.status === 2 ? "禁用" : "启用"
  	  }</strong><strong style='color:var(--el-color-primary)'>${
  		row.name
  	  }</strong>菜单吗?`,
  	  "系统提示",
  	  {
  		confirmButtonText: "确定",
  		cancelButtonText: "取消",
  		type: "warning",
  		dangerouslyUseHTMLString: true,
  		draggable: true
  	  }
  	)
  	  .then(async() => {
  		let params = {
  			userId: row.userId,
  			status: row.status === 2 ? 2 : 1
  		}
  		await updateUserStatusApi(params);
  		onSearch()
  		
  		message("已成功修改用户状态", {
  			type: "success"
  		});
  	  })
  	  .catch(() => {
  		row.status === 2 ? (row.status = 1) : (row.status = 2);
  	  });
  }
  /* 获取菜单树*/
  async function getMenuListTree() {
	  const { result} = await getRbacMenuListTreeApi();
	  return result;
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await getRbacMenuListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.page.total;
    pagination.pageSize = result.page.perPage;
    pagination.currentPage = result.page.totalPage;
    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  // 删除参数为空的键值
  function cleanEmptyData(obj: object) {
    Object.keys(obj).forEach(key => {
      if (obj[key] == null || obj[key] == '') {
        delete obj[key];
      }
    });
	return obj
  }
  const formInline = ref();
  async function openDialog(title = "新增", row?: FormItemProps) {
    if (`${title}` == "新增") {
      formInline.value = {
        title: "新增",
		higherDeptOptions: await getMenuListTree(),
		status: 1,
		linkType: 1,
		isPageMenu: 1,
		sort: 0,
		firstMenuId: null,
		secondMenuId: null,
		thirdMenuId: null,
		fourthMenuId: null,
		parMenuId: null,
      };
    } else {
      const { result } = await getRbacMenuShowApi({ menuId: row.menuId });
	  console.log(result?.fourthMenuId? result.fourthMenuId : result?.thirdMenuId?result.thirdMenuId:result?.secondMenuId?result.secondMenuId:result?.firstMenuId)
      formInline.value = {
        title: "修改",
		higherDeptOptions: await getMenuListTree(),
		parMenuId: result?.fourthMenuId? Number(result.fourthMenuId) : result?.thirdMenuId?Number(result.thirdMenuId):result?.secondMenuId?Number(result.secondMenuId):Number(result.firstMenuId),
        menuId: row?.menuId ?? "",
        parentId: row?.parentId ?? "",
        level: result?.level ?? "",
        name: result?.name ?? "",
        path: row?.path ?? "",
        icon: result?.icon ?? "",
        status: result?.status ?? "",
        linkType: result?.linkType ?? "",
        isPageMenu: result?.isPageMenu ?? "",
        linkUrl: result?.linkUrl ?? "",
        firstMenuId: result?.firstMenuId ?? "",
        secondMenuId: result?.secondMenuId ?? "",
        thirdMenuId: result?.thirdMenuId ?? "",
        fourthMenuId: result?.fourthMenuId ?? "",
        sort: result?.sort ?? 0,
		dataPermission: result?.dataPermission ?? "",
      };
    }
    addDialog({
      title: `${title}菜单`,
      props: {
        formInline: formInline
      },
      width: "44%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
		
        const curData = options.props.formInline as FormItemProps;
		const params = {
			menuId: curData.menuId,
			name: curData.name,
			level: curData.level,
			icon: curData.icon,
			linkType: curData.linkType,
			isPageMenu: curData.isPageMenu,
			linkUrl: curData.linkUrl,
			sort: curData.sort,
			firstMenuId: curData.firstMenuId,
			secondMenuId: curData.secondMenuId,
			thirdMenuId: curData.thirdMenuId,
			fourthMenuId: curData.fourthMenuId,
			dataPermission: curData.dataPermission
		}
        function chores() {
          message(`您${title}了工作计划`, {
            type: "success"
          });
          done();
          onSearch();
        }
		
        FormRef.validate(valid => {
          if (valid) {
            if (title === "新增") {
              createRbacMenuApi(cleanEmptyData(params))
                .then(() => {
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            } else {
              updateRbacMenuApi(cleanEmptyData(params))
                .then(() => {
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();
	getMenuListTree()
  });

  function handleDelete(row) {
    delRbacMenuApi({ menuId: row.menuId }).then(() => {
      message(`删除成功`, { type: "success" });
      onSearch();
    });
  }
  function confirmStatus() {
    alert("审核通过");
  }
  function refusedStatus() {
    alert("审核拒绝");
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
    confirmStatus,
    refusedStatus,
	
  };
}
